/*
 * @(#)org.example.netty.http 2020/4/1/0001
 *
 * Copy Right@ 人人译视界
 */


package org.example.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/4/1/0001
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

	/**
	 *
	 * @param channelHandlerContext
	 * @param httpObject  客户端和服务端通讯的数据被封装成HttpObject
	 * @throws Exception
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
		// 判断httpObject是否是一个HttpRequest请求
		if (httpObject instanceof HttpRequest) {
			System.out.println("pipeline hash=" + channelHandlerContext.pipeline().hashCode() +",channel hash=" + channelHandlerContext.channel().hashCode());
			System.out.println("msg 类型：" + httpObject.getClass());
			System.out.println("客户端地址：" + channelHandlerContext.channel().remoteAddress());
			HttpRequest request = (HttpRequest) httpObject;
			URI uri = new URI(request.getUri());
			if ("/favicon.ico".equals(uri.getPath())) {
				System.out.println("请求了favicon.ico资源，不作响应");
				return;
			}
			// 回复信息给浏览器(http协议)
			ByteBuf buf = Unpooled.copiedBuffer("<html><head><meta charset='utf-8'/></head><body>hello，我是服务端</body></html>", CharsetUtil.UTF_8);
			// 构造一个http的响应，即httpResponse
			DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
			response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
			response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
			// 将构建好的response返回
			channelHandlerContext.writeAndFlush(response);
		}
	}
}
